﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Amba.Workflow.Models;
using Orchard;
using Orchard.Data;

namespace Amba.Workflow.Services
{
    public interface IPeriodicalEventService : IDependency
    {
        PeriodicalEventInfoRecord GetPeriodicalEventInfo(int eventId);
        void SetLastRunDate(int eventId);
    }

    public class PeriodicalEventService : IPeriodicalEventService
    {
        private readonly IRepository<PeriodicalEventInfoRecord> _periodicalEventInfoRepo;

        public PeriodicalEventService(IRepository<PeriodicalEventInfoRecord> periodicalEventInfoRepo)
        {
            _periodicalEventInfoRepo = periodicalEventInfoRepo;
        }

        public PeriodicalEventInfoRecord GetPeriodicalEventInfo(int eventId)
        {
            var infoRecord = _periodicalEventInfoRepo.Table.FirstOrDefault(x => x.EventId == eventId);
            if (infoRecord == null)
            {
                infoRecord = new PeriodicalEventInfoRecord() { EventId = eventId, LastRun = DateTime.UtcNow };
                _periodicalEventInfoRepo.Create(infoRecord);
            }
            return infoRecord;
        }

        public void SetLastRunDate(int eventId)
        {
            var infoRecord = GetPeriodicalEventInfo(eventId);
            infoRecord.LastRun = DateTime.UtcNow;
            _periodicalEventInfoRepo.Update(infoRecord);
        }
    }
}